import { Effect, ImmerReducer, history } from 'umi'
import { message } from 'antd'
import { loginFn } from '../services/admin'

export interface IAdminModel {
    namespace: 'admin';
    state: {
        isLogin: boolean,
        adminname: string,
        role: number,
        token: string
    }
    effects: {
        loginAction: Effect;
    },
    reducers: {
        CHANGE_LOGIN_STATE: ImmerReducer,
        CHANGE_ADMIN_NAME: ImmerReducer,
        CHANGE_ROLE: ImmerReducer,
        CHANGE_TOKEN: ImmerReducer,
    }
}

const AdminModel: IAdminModel = {
    namespace: 'admin',
    state: {
        isLogin: localStorage.getItem('isLogin') === 'true',
        adminname: localStorage.getItem('adminname') || '',
        role: Number(localStorage.getItem('role')) || 1,
        token: localStorage.getItem('token') || ''
    },

    effects: {
        *loginAction({ payload }: any, { call, put }: { call: Function, put: Function }) {
            const res = yield call(loginFn, payload)
            if (res.data.code === '10003') {
                message.error('密码错误')
            } else if (res.data.code === '10005') {
                message.error('该账户不可用')
            } else {
                message.success('登录成功')
                yield put({
                    type: 'CHANGE_LOGIN_STATE',
                    payload: true
                })
                yield put({
                    type: 'CHANGE_ADMIN_NAME',
                    payload: res.data.data.adminname
                })
                yield put({
                    type: 'CHANGE_ROLE',
                    payload: res.data.data.role
                })
                yield put({
                    type: 'CHANGE_TOKEN',
                    payload: res.data.data.token
                })
                history.push('/')
            }
        }
    },
    reducers: {
        CHANGE_LOGIN_STATE(state, action) {
            localStorage.setItem('isLogin', String(action.payload))
            return {
                ...state,
                isLogin: action.payload
            }
        },
        CHANGE_ADMIN_NAME(state, action) {
            localStorage.setItem('adminname', action.payload)
            return {
                ...state,
                adminname: action.payload
            }
        },
        CHANGE_ROLE(state, action) {
            localStorage.setItem('role', String(action.payload))
            return {
                ...state,
                role: action.payload
            }
        },
        CHANGE_TOKEN(state, action) {
            localStorage.setItem('token', action.payload)
            return {
                ...state,
                token: action.payload
            }
        }
    }
};

export default AdminModel